package top.leinx.fxnotes.properties;

/**
 * @Author : xiaolei
 * @DateTime: 2021/3/12 1:46 下午
 */

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.util.concurrent.atomic.AtomicReference;

public class PropertyBindExample extends Application {
    AtomicReference<Double> rect2XOffset = new AtomicReference<>((double) 0);
    AtomicReference<Double> rect2YOffset = new AtomicReference<>((double) 0);

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();

        Pane pane = new Pane();

        Rectangle rect1 = new Rectangle(40.0, 30.0, Color.RED);
        Rectangle rect2 = new Rectangle(40.0, 30.0, Color.BLUE);

        rect2.setOnMousePressed(mouseEvent -> {
            rect2XOffset.set(mouseEvent.getX() - rect2.getX());
            rect2YOffset.set(mouseEvent.getY() - rect2.getY());
        });

        rect2.setOnMouseDragged(mouseEvent -> {
            rect2.setX(mouseEvent.getX() - rect2XOffset.get());
            rect2.setY(mouseEvent.getY() - rect2YOffset.get());
        });

        rect2.setOnMouseReleased(mouseEvent -> {
            if (rect2.getY() < 0) {
                rect2.setY(0);
            }
            if (rect2.getX() < 0) {
                rect2.setX(0);
            }
        });

        rect1.setX(20.0);
        rect1.setY(20.0);
        rect2.setX(200.0);
        rect2.setY(100.0);

        Line line = new Line();
        line.startXProperty().bind(rect1.xProperty().add(rect1.widthProperty()));
        line.startYProperty().bind(rect1.yProperty().add(rect1.heightProperty().divide(2.0)));
        line.endXProperty().bind(rect2.xProperty());
        line.endYProperty().bind(rect2.yProperty().add(rect2.heightProperty().divide(2.0)));

        pane.getChildren().addAll(rect1, rect2, line);

        ScrollPane sp = new ScrollPane(pane);
        sp.setStyle("-fx-padding: 10px; -fx-background-color: gray;");
        pane.backgroundProperty().set(Background.EMPTY);

        root.setCenter(sp);

        Scene scene = new Scene(root, 640, 400, true); // pane的宽度变化，触发对该属性的监听
        primaryStage.setScene(scene);
        primaryStage.setTitle("属性绑定示例");

        primaryStage.show();
    }
}
